package com.example.wjy;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.example.room.entity.Master;
import com.example.superyi.myteam.databinding.ActivityRecommendBinding;
import com.example.wjy.adapter.RecommendAdapter;
import com.example.wjy.fragments.MasterFragment;
import com.example.wjy.viewmodels.MasterViewModel;
import com.example.wjy.viewmodels.RecommendViewModel;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RecommendActivity extends AppCompatActivity {

    /**
     * DataBinding of this activity and activity_recommend.
     */
    ActivityRecommendBinding binding;

    /**
     * The adapter of ViewPager2.
     */
    RecommendAdapter adapter;

    /**
     * ViewModel of this activity.
     */
    RecommendViewModel recommendViewModel;

    /**
     * ViewModel of fragment in this activity to control data stream from database.
     */
    MasterViewModel masterViewModel;

    List<Master> masters;

    String url = "http://49.232.60.155:8080/AppServer_war/TeamServlet";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRecommendBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        recommendViewModel = new ViewModelProvider(this).get(RecommendViewModel.class);
        masterViewModel = new ViewModelProvider(this).get(MasterViewModel.class);

//        masterViewModel.insertMasters(new Master("wang", "junyan"));
        //添加5个碎片到此activity中
        List<Fragment> fragmentList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            fragmentList.add(new MasterFragment());
        }

        //ViewPager2的适配器
        adapter = new RecommendAdapter(this, fragmentList);
        binding.viewPager2.setAdapter(adapter);
        binding.viewPager2.setOffscreenPageLimit(5);

        binding.viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                new Thread(() -> {
                    String label = recommendViewModel.tabList.get(position);
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("label",label)
                            .add("flag","7")
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    Call call = client.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {

                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            String json = response.body().string();
                            Gson gson = new Gson();
                            masters = gson.fromJson(json,new TypeToken<List<Master>>() {}.getType());
                            masterViewModel.deleteAllMaster();
                            if(masters != null)
                                for(int i = 0;i < masters.size();++i) {
                                    masterViewModel.insertMasters(masters.get(i));
                                }
                        }
                    });
                }).start();

            }
        });
        //设置TabLayout
        new TabLayoutMediator(binding.tabLayout, binding.viewPager2, (tab, position) -> {
            TextView tabView = new TextView(RecommendActivity.this);
            tabView.setText(recommendViewModel.tabList.get(position));
            tabView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
            tab.setCustomView(tabView);
        }).attach();
    }
}